package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    public void saveOrUpdate(Employee entity) {
        if (entity.getId() == null) {
            entity.setState(true);
            // 加密密码
            String password = entity.getPassword();
            if (password != null) {
                Md5Hash hash = new Md5Hash(password, "Fizz_kai", 2);
                entity.setPassword(hash.toString());
            }
            employeeMapper.insert(entity);
        } else {
            // 删除 employee_role
            employeeMapper.deleteRoleRelation(entity.getId());
            employeeMapper.updateByPrimaryKey(entity);
        }
        // 维护 employee_role
        for (Role role : entity.getRoles()) {
            employeeMapper.insertRoleRelation(entity.getId(), role.getId());
        }
    }

    public void delete(Long id) {
        // 删除 employee_role
        employeeMapper.deleteRoleRelation(id);
        employeeMapper.deleteByPrimaryKey(id);
    }

    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        int count = employeeMapper.queryCount(qo);
        if (count == 0) {
            return new PageResult(0, Collections.emptyList());
        }
        List<Employee> employees = employeeMapper.queryList(qo);
        return new PageResult(count, employees);
    }

    @Override
    public Employee getByUsername(String name) {
        return employeeMapper.selectByUsername(name);
    }

    @Override
    public void changeState(Long id) {
        employeeMapper.changeState(id);
    }

    @Override
    public boolean validateUsernname(String name, Long id) {
        Employee emp = employeeMapper.selectByUsername(name);
        return emp == null || emp.getId() == id;
    }

    @Override
    public List<Map<String,Object>> selectName() {
        return employeeMapper.selectName();
    }

}
